#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <poll.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main() {
    int ret, readret;
    int mousefd;
    char buf[100];
    int mousepos;

    mousefd = open("/dev/input/mouse0", O_RDONLY);
    if (mousefd < 0) {
        perror("open mouse error");
        exit(0);
    }

    struct pollfd fds[2];
    int nfds = sizeof(fds) / sizeof(fds[0]);

    fds[0].fd = 0;
    fds[0].events = POLLIN;
    
    fds[1].fd = mousefd;
    fds[1].events = POLLIN;

    int timeout = 2000; // 等待的ms数
    
    while (1) {
        do {
            ret = poll(fds, nfds, timeout);
        } while (ret < 0 && errno == EINTR);

        if (ret > 0) { // 监控的fds有动静的数量
            if (fds[0].events == fds[0].revents) {
                memset(buf, 0, sizeof (buf));
                readret = read(fds[0].fd, buf, sizeof(buf));
                if (readret > 0) printf("%s\n", buf);
            }

            if (fds[1].events == fds[1].revents) {
                mousepos = 0;
                readret = read(fds[1].fd, &mousepos, sizeof(mousepos));
                if (readret > 0) printf("%d\n", mousepos);
            }
        }
        else if (ret == 0) {
            printf("time out\n");
        }
    }
    
    close(mousefd);
    return 0;
}

